/* eslint-disable react-refresh/only-export-components */
import { createContainer } from "unstated-next";
import { IFile } from "./typings";
import { useCallback, useMemo, useState } from "react";
import { getFileType, maxSequenceTabName } from "./utils";
import importMap from "./template/import-map.json?raw";
import App from "./template/App.tsx?raw";
import AppCss from "./template/App.css?raw";
import { COMPILER_FILE_ENUM } from "./enum";

function useContainer() {
  // 存储文件列表
  const [files, setFiles] = useState<{
    [key: string]: IFile;
  }>({
    // app文件
    [COMPILER_FILE_ENUM.APP_FILE_NAME]: {
      name: COMPILER_FILE_ENUM.APP_FILE_NAME,
      type: getFileType(COMPILER_FILE_ENUM.APP_FILE_NAME),
      value: App,
    },
    // css文件
    [COMPILER_FILE_ENUM.APP_CSS_FILE_NAME]: {
      name: COMPILER_FILE_ENUM.APP_CSS_FILE_NAME,
      type: getFileType(COMPILER_FILE_ENUM.APP_CSS_FILE_NAME),
      value: AppCss,
    },
    // es映射文件
    [COMPILER_FILE_ENUM.IMPORT_MAP_FILE_NAME]: {
      name: COMPILER_FILE_ENUM.IMPORT_MAP_FILE_NAME,
      type: getFileType(COMPILER_FILE_ENUM.IMPORT_MAP_FILE_NAME),
      value: importMap,
    },
  });

  // 当前选中的文件
  const [currentFileName, setCurrentFileName] = useState("App.tsx");

  // 创建一个key用于作为引入的mapJson文件的key
  const previewKey = useMemo(() => {
    return JSON.stringify(
      files?.[COMPILER_FILE_ENUM.IMPORT_MAP_FILE_NAME]?.value
    );
  }, [files]);

  // 文件删除
  const handleFileDelete = useCallback(
    (name: string) => {
      setFiles((prev) => {
        const newFiles = { ...prev };
        delete newFiles[name];
        return newFiles;
      });
      if (name === currentFileName) {
        setCurrentFileName("App.tsx");
      }
    },
    [currentFileName]
  );

  // 文件添加
  const handleFileAdd = useCallback(() => {
    const name = maxSequenceTabName(Object.keys(files));
    setFiles((prev) => {
      return {
        ...prev,
        [name]: {
          name,
          type: getFileType(name),
          value: "",
        },
      };
    });
  }, [files, setFiles]);

  return {
    files,
    previewKey,
    setFiles,
    currentFileName,
    setCurrentFileName,
    handleFileAdd,
    handleFileDelete,
  };
}

const Container = createContainer(useContainer);

export type ContainerType = typeof useContainer;

export { useContainer };

export default Container;
